package com.hnhegui.backend.interceptor;

import com.hnhegui.backend.exception.BusinessException;
import com.hnhegui.backend.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 认证拦截器
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头获取Token
        String authorization = request.getHeader("Authorization");
        
        if (authorization == null || !authorization.startsWith("Bearer ")) {
            throw new BusinessException(40101, "未提供认证令牌");
        }

        // 提取Token
        String token = authorization.substring(7);

        // 验证Token格式和有效期
        if (!jwtUtil.validateToken(token)) {
            throw new BusinessException(40101, "认证令牌无效或已过期");
        }

        // 获取用户信息
        Long userId = jwtUtil.getUserIdFromToken(token);
        String username = jwtUtil.getUsernameFromToken(token);
        String role = jwtUtil.getRoleFromToken(token);

        if (userId == null) {
            throw new BusinessException(40101, "认证令牌解析失败");
        }

        // 验证Redis中Token是否存在
        if (!jwtUtil.validateToken(token, userId)) {
            throw new BusinessException(40101, "认证令牌已失效");
        }

        // 将用户信息存入请求属性
        request.setAttribute("userId", userId);
        request.setAttribute("username", username);
        request.setAttribute("role", role);

        return true;
    }
}
